﻿namespace Algo.Demo
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class Program
    {
        public static void Main()
        {
            var array = GenerateItems(1000).ToArray();
            
            Console.WriteLine("Sort strategies:");
            foreach (var strategy in Strategies.GetSortStrategies())
            {
                TestSortStrategy(strategy, array);
                var result = TestSortStrategy(strategy, array);
                Console.WriteLine(result);
            }

            var sortedList = AlgoFactory.CreateQuickSortStrategy().Sort(array).ToArray();
            Console.WriteLine("Dichotomy search strategies:");
            foreach (var strategy in Strategies.GetDichotomySearchStrategy())
            {
                TestDichotomySearchStrategy(strategy, sortedList);
                var result = TestDichotomySearchStrategy(strategy, sortedList);
                Console.WriteLine(result);
            }

            Console.ReadLine();
        }

        private static IEnumerable<int> GenerateItems(int count)
        {
            var rnd = new Random();
            for (int i = 0; i < count; i++)
            {
                yield return rnd.Next(count);
            }
        }

        private static TestResult TestSortStrategy(ISortStrategy sortStrategy, IEnumerable<int> array)
        {
            var result = new TestResult(sortStrategy.GetType());
            result.Start();
            sortStrategy.Sort(array, Int32EqualityComparer.Instance, result);
            result.Stop();
            return result;
        }

        private static TestResult TestDichotomySearchStrategy(IDichotomySearchStrategy strategy, IList<int> list)
        {
            int? prev;
            int? next;
            strategy.Find(list, 0, out prev, out next);
            var result = new TestResult(strategy.GetType());
            result.Start();
            foreach (var item in list)
            {
                var res = strategy.Find(list, item, Int32EqualityComparer.Instance, result, out prev, out next);
                if (res != true)
                {
                    throw new InvalidOperationException("Algoritm");
                }
            }

            result.Stop();
            return result;
        }
    }
}
